﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QuanLyDeTaiKHCN.Obj_class;
using System.IO;
namespace QuanLyDeTaiKHCN.UserControls.Manager
{
    public partial class TheoDoiTienDoKinhPhi : System.Web.UI.UserControl
    {
        _dbDataContext _db = new _dbDataContext();
        public SecurityLib.Sec_AES _ps = new SecurityLib.Sec_AES();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string str = Request.QueryString["id"].Replace(" ", "+");
                string madetai = _ps.Decrypt(str, "gold", 128);
                if (_db.tblTheoDoiHopDongs.Where(r => r.MaDeTai.Trim() == madetai).Count() == 0)
                {
                    lblmessage.Text = "Đề tài này chưa ký hợp đồng.";
                    lblmessage.Visible = true;
                    pntcontent.Visible = false;
                }
                else
                {
                    lblmessage.Visible = false;
                    pntcontent.Visible = true;
                    BindGrid(madetai);
                    BindDataToGiaDoan(madetai);
                }
            }
        }
        protected void BindDataToGiaDoan(string madetai)
        {
            drlGiaiDoan.Items.Clear();
            var list = _db.tblTheoDoiHopDongs.Single(r => r.MaDeTai.Trim() == madetai);
            ListItem item = new ListItem("---Chọn giai đoạn---", "-1");
            drlGiaiDoan.Items.Add(item);
            string[] gds = list.GiaiDoanThucHien.Split('@');
            int count = 0;
            for (int i = 0; i < gds.Length; i++)
            {
                if (gds[i].Split('!')[0].Length == 0)
                    break;
                else
                    count++;
            }
            for (int i = 0; i < count; i++)
            {
                item = new ListItem("Giai đoạn " + (i + 1).ToString(), gds[i].Split('!')[0]);
                drlGiaiDoan.Items.Add(item);
            }
        }
        protected void drlGiaiDoan_SelectedIndexChanged(object sender, EventArgs e)
        {
            string str = Request.QueryString["id"].Replace(" ", "+");
            string madetai = _ps.Decrypt(str, "gold", 128);
            var list = _db.tblTheoDoiHopDongs.Single(r => r.MaDeTai.Trim() == madetai);
            string[] gds = list.GiaiDoanThucHien.Split('@');
            string[] gd = gds[int.Parse(drlGiaiDoan.SelectedIndex.ToString()) - 1].Split('!');
            txtThoiGianThucHienTu.Text = string.Format("{0:dd/MM/yyyy}", gd[0]);
            txtThoiGianThucHienDen.Text = string.Format("{0:dd/MM/yyyy}", gd[1]);
            txtKinhPhi.Text = gd[2];
            BindDataToControls(int.Parse(drlGiaiDoan.SelectedIndex.ToString()), madetai);
            lblstatus.Text = "";
        }
        protected void BindDataToControls(int giaidoan, string madetai)
        {
            try
            {
                var item = _db.tblKiemTraTienDoKinhPhis.Single(r => r.MaDeTai.Trim() == madetai && r.GiaiDoan == giaidoan);
                txtSoBienBanQuyetToan.Text = item.SoBienBanQuyetToanKinhPhi.Trim();
                txtNgayQuyetToan.Text = string.Format("{0:dd/MM/yyyy}", item.NgayQuyetToan);
                txtNoiDungQuyetToan.Text = item.NoiDungQuyetToan.Trim();
                txtKinhPhiQuyetToan.Text = item.KinhPhiQuyetToan.ToString();
                txtKinhPhiThucChuyen.Text = item.KinhPhiThucChuyen.ToString();
                txtNgayChuyenKinhPhi.Text = string.Format("{0:dd/MM/yyyy}", item.NgayChuyenKinhPhi);

            }
            catch
            {
                txtSoBienBanQuyetToan.Text = "";
                txtNgayQuyetToan.Text = "";
                txtNoiDungQuyetToan.Text = "";
                txtKinhPhiQuyetToan.Text = "";
                txtKinhPhiThucChuyen.Text = "";
                txtNgayChuyenKinhPhi.Text = "";
            }
        }
        protected void btnsave_Click(object sender, EventArgs e)
        {
            string str = Request.QueryString["id"].Replace(" ", "+");
            string madetai = _ps.Decrypt(str, "gold", 128);
            try
            {
                var _tb = _db.tblKiemTraTienDoKinhPhis.Single(r=>r.MaDeTai.Trim()==madetai && r.GiaiDoan==int.Parse(drlGiaiDoan.SelectedIndex.ToString()));
                _tb.GiaiDoan = int.Parse(drlGiaiDoan.SelectedIndex.ToString());
                _tb.SoBienBanQuyetToanKinhPhi = txtSoBienBanQuyetToan.Text;
                if (CatalogAccess.ConvertToDateBool(txtNgayQuyetToan.Text))
                    _tb.NgayQuyetToan = CatalogAccess.ConvertToDate(txtNgayQuyetToan.Text);
                _tb.NoiDungQuyetToan = txtNoiDungQuyetToan.Text;
                _tb.KinhPhiQuyetToan = int.Parse(txtKinhPhiQuyetToan.Text);
                _tb.KinhPhiThucChuyen = int.Parse(txtKinhPhiThucChuyen.Text);
                if (CatalogAccess.ConvertToDateBool(txtNgayChuyenKinhPhi.Text))
                    _tb.NgayChuyenKinhPhi = CatalogAccess.ConvertToDate(txtNgayChuyenKinhPhi.Text);
                try
                {
                    _db.SubmitChanges();
                    lblstatus.Text = "Đã lưu.";
                }
                catch { lblstatus.Text = "Không lưu được."; }
            }
            catch//truong hop them moi
            {
                tblKiemTraTienDoKinhPhi _tb = new tblKiemTraTienDoKinhPhi();
                _tb.MaDeTai = madetai;
                _tb.GiaiDoan = int.Parse(drlGiaiDoan.SelectedIndex.ToString());
                _tb.SoBienBanQuyetToanKinhPhi = txtSoBienBanQuyetToan.Text;
                if (CatalogAccess.ConvertToDateBool(txtNgayQuyetToan.Text))
                    _tb.NgayQuyetToan = CatalogAccess.ConvertToDate(txtNgayQuyetToan.Text);
                _tb.NoiDungQuyetToan = txtNoiDungQuyetToan.Text;
                _tb.KinhPhiQuyetToan = int.Parse(txtKinhPhiQuyetToan.Text);
                _tb.KinhPhiThucChuyen = int.Parse(txtKinhPhiThucChuyen.Text);
                if (CatalogAccess.ConvertToDateBool(txtNgayChuyenKinhPhi.Text))
                    _tb.NgayChuyenKinhPhi = CatalogAccess.ConvertToDate(txtNgayChuyenKinhPhi.Text);
                try
                {
                    _db.tblKiemTraTienDoKinhPhis.InsertOnSubmit(_tb);
                    _db.SubmitChanges();
                    lblstatus.Text = "Đã lưu.";
                }
                catch { lblstatus.Text = "Không lưu được."; }
            }
        }

        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string str = Request.QueryString["id"].Replace(" ", "+");
            string madetai = _ps.Decrypt(str, "gold", 128);
            var item = _db.tblFiles.Single(r => r.ID == int.Parse(grid.DataKeys[e.RowIndex].Value.ToString()));
            try
            {
                _db.tblFiles.DeleteOnSubmit(item);
                _db.SubmitChanges();
                try
                {
                    string filename = ((Label)grid.Rows[e.RowIndex].FindControl("lblFileName")).Text;
                    System.IO.File.Delete(Server.MapPath(PageURL.local + "filehoso/" + filename));
                }
                catch { }
                BindGrid(madetai);
            }
            catch { }
        }

        protected void LinkAddFile_Click(object sender, EventArgs e)
        {
            if (filebienban.HasFile)
            {
                string str = Request.QueryString["id"].Replace(" ", "+");
                string madetai = _ps.Decrypt(str, "gold", 128);
                DateTime t = DateTime.Now;
                string filename = (t.Day < 10 ? "0" + t.Day.ToString() : t.Day.ToString()) + (t.Month < 10 ? "0" + t.Month.ToString() : t.Month.ToString()) + t.Year.ToString() + t.Hour.ToString() + t.Minute.ToString() + t.Second.ToString() + Path.GetExtension(filebienban.FileName);
                tblFile _tb = new tblFile();
                _tb.MaDeTaiDuAn = madetai;
                _tb.FileThuyetMinh = filename;
                _tb.GhiChuFileThuyetMinh = txtghichufilethuyetminh.Text;
                _tb.NgayNhanThuyetMinh = CatalogAccess.ConvertToDate(txtNgayNhan.Text);
                _tb.FileCuaBuoc = 8;
                try
                {
                    _db.tblFiles.InsertOnSubmit(_tb);
                    _db.SubmitChanges();
                    BindGrid(madetai);
                    filebienban.SaveAs(Server.MapPath(PageURL.local + "filehoso/" + filename));
                    txtghichufilethuyetminh.Text = "";
                }
                catch { }
            }
        }
        protected void BindGrid(string madetai)
        {
            var list = from p in _db.tblFiles.Where(r => r.MaDeTaiDuAn.Trim() == madetai && r.FileCuaBuoc == 8)
                       select new
                       {
                           ID = p.ID,
                           TrichYeu = p.GhiChuFileThuyetMinh.Trim(),
                           NgayLuu = string.Format("{0:dd/MM/yyyy}", p.NgayNhanThuyetMinh),
                           FileThuyetMinh = p.FileThuyetMinh.Trim(),
                           //sau khi up len host thi xai link1:
                           //Fileonline =domain_name + "\\" +directory+"\\"+ p.FileThuyetMinh.Trim()
                           //test xaif link2
                           //Fileonline = "localhost\\" +directory+"\\"+ p.FileThuyetMinh.Trim()
                           //demo link3:
                           Fileonline = "http://thongkekhcnbd.khcnbinhduong.gov.vn/userfiles/vanban/9475707965_493_296.pdf"

                       };
            grid.DataSource = list.ToList();
            grid.DataBind();
        }

    }
}